import {Component} from "react";
import {connect} from "umi";
import React from "react";
import APIS from "@/apis";
import HighPerformTable from "@/components/HighPerformTable";
import {Button, DatePicker, Form, Input, Select, Space} from "antd";
import {PlusOutlined} from "@ant-design/icons";
import Modal from "antd/lib/modal/Modal";
import moment from "moment";
import FilterByCourse from "@/components/FilterByCourse";

class TestManager extends Component<any> {
  actionRef: any;
  state = {
    allCourse: [],
    renderTable: true,
    modalVisible: false,
    modalData: {id: null, examName: '', description: '', title: null, startTime: '', endTime: ''},
    allExam: [],
    courseId: 0,
    paperId: 0,
    filter: 0
  }

  componentDidMount() {
    APIS.CourseAPI.GetCourseList({
      current: 1,
      pageSize: 99999,
      state: -1
    }).then(res => this.setState({allCourse: res.data})).catch(e => {
      console.error(e)
    })
  }

  requestGetData(
    params: {
      pageSize?: number;
      current?: number;
    },
    sorter: {
      [key: string]: 'ascend' | 'descend';
    },
    filter: {
      [key: string]: React.ReactText[];
    },
  ) {
    return APIS.ExamAPI.GetTestList({...params, sorter, filter, id: this.state.filter});
  }

  clomns: any = [
    {
      title: '考试名称',
      dataIndex: 'examName',
      width:"25%",
      ellipsis:true,
    },
    {
      title: '考试描述',
      dataIndex: 'description',
      width:"20%",
      ellipsis:true,
    },
    {
      title: '使用试卷',
      dataIndex: 'title',
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      render: (record: any) => (
        <span>
          {
            moment(record).format("YYYY-MM-DD hh:mm:ss")
          }
        </span>
      )
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      render: (record: any) => (
        <span>
          {
            moment(record).format("YYYY-MM-DD hh:mm:ss")
          }
        </span>
      )
    },
    // {
    //     title: '所属课程',
    //     dataIndex: 'courseId',
    //     render: (record: any) => (
    //         this.state.allCourse.map((v: any) => (
    //             v.id === record ? v.courseName : null
    //         ))
    //     )
    // },
  ];

  onCourseSelectChange(e: any, info: any) {
    const id = parseInt(info.key);
    this.setState({courseId: id})
    APIS.ExamAPI.GetExamList({
      current: 1,
      pageSize: 99999,
      courseId: id
    }).then(res => this.setState({allExam: res.data}))
  }

  onPaperSelectChange(e: any, info: any) {
    const id = parseInt(info.key);
    this.setState({paperId: id})
  }

  getExamData() {
    setTimeout(() => {
      if (this.state.modalData.id !== null) {
        APIS.ExamAPI.GetExamList({
          current: 1,
          pageSize: 99999,
          courseId: 0
        }).then(res => this.setState({allExam: res.data}))
      }
    }, 100);
  }

  render() {
    const {RangePicker} = DatePicker
    const {modalData, allCourse, courseId} = this.state;
    return (
      <div>
        <FilterByCourse
          course={allCourse}
          getValue={(value) => {
            this.setState({filter: value});
            this.actionRef?.reload();
          }}/>
        {
          this.state.renderTable &&
          <HighPerformTable<any>
            columns={this.clomns}
            requestGetData={this.requestGetData.bind(this)}
            ref={(ref) => (this.actionRef = ref)}
            onClickUpdate={record => {
              // console.log(record)
              this.setState({modalVisible: true, modalData: record, paperId: record.paperId});
              this.getExamData();
            }}
            handleChangeState={(data, state) => {
              return APIS.ExamAPI.ChangeTestState({id: data.id, state: state === true ? 1 : 0})
            }}
            handleDelete={id => {
              return APIS.ExamAPI.DeleteTest({id: id})
            }}
            toolBarRender={() => [
              <Button key='0' type="primary" onClick={() => {
                this.setState({modalVisible: true, modalData: {id: null}});
                this.getExamData();
              }}>
                <PlusOutlined/> 新增考试
              </Button>,
            ]
            }
          />
        }
        <Modal
          title={modalData?.id ? "编辑考试" : "新增考试"}
          visible={this.state.modalVisible}
          destroyOnClose={true}
          onCancel={() => this.setState({modalVisible: false, modalData: {id: null}, courseId: 0})}
          footer={<div></div>}
        >
          {
            this.state.modalVisible &&
            <Form
              initialValues={{
                examName: this.state.modalData?.examName,
                description: this.state.modalData?.description,
                paperId: this.state.modalData?.title,
                startTime: this.state.modalData?.startTime,
                endTime: this.state.modalData?.endTime,
              }}
              onFinish={values => {
                if (this.state.modalData.id !== null) {
                  APIS.ExamAPI.UpdateTest({
                    id: this.state.modalData.id,
                    examName: values.examName,
                    description: values.description,
                    paperId: this.state.paperId,
                    startTime: moment(this.state.modalData.startTime).format("YYYY-MM-DD hh:mm:ss"),
                    endTime: moment(this.state.modalData.endTime).format("YYYY-MM-DD hh:mm:ss"),
                  }).then(() => {
                    this.setState({renderTable: false, modalVisible: false})
                    this.setState({renderTable: true, modalData: {id: null}})
                  }).catch(e => console.error(e)
                  )
                } else {
                  APIS.ExamAPI.CreateNewTest({
                    examName: values.examName,
                    description: values.description,
                    paperId: this.state.paperId,
                    startTime: moment(this.state.modalData.startTime).format("YYYY-MM-DD hh:mm:ss"),
                    endTime: moment(this.state.modalData.endTime).format("YYYY-MM-DD hh:mm:ss"),
                  }).then(() => {
                    this.setState({renderTable: false, modalVisible: false})
                    this.setState({renderTable: true, modalData: null})
                  }).catch(e => console.error(e)
                  )
                }
              }}
            >
              <Form.Item
                label='考试名称'
                name='examName'
                rules={[{required: true, message: '请输入考试名称'}]}
              >
                <Input/>
              </Form.Item>
              <Form.Item
                label='考试描述'
                name='description'
                rules={[{required: true, message: '请输入考试描述'}]}
              >
                <Input/>
              </Form.Item>
              {
                !modalData.id ?
                  <Form.Item
                    label='考试课程'
                    name='testlesson'
                    rules={[{required: true, message: '请选择考试课程'}]}
                  >
                    <Select defaultValue={""} onChange={this.onCourseSelectChange.bind(this)}
                            showSearch={true}
                    >
                      {allCourse.map?.((v: any, i) => (
                        <Select.Option key={v.id} value={v.courseName}>{v.courseName}</Select.Option>
                      ))}
                    </Select>
                  </Form.Item> : null
              }

              <Form.Item
                label='考试试卷'
                name='paperId'
                rules={[{required: true, message: '请选择考试试卷'}]}
              >
                <Select disabled={courseId === 0 && modalData.id === null} showSearch
                        onChange={this.onPaperSelectChange.bind(this)}>
                  {this.state.allExam.map?.((v: any, i) => (
                    <Select.Option key={v.id} value={v.title}>{v.title}</Select.Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item
                label='起止时间'
                name='time'
                rules={[{required: true, message: '请设置起止时间'}]}
              >
                <RangePicker
                  defaultValue={this.state.modalData.id !== null ? [moment(this.state.modalData.startTime), moment(this.state.modalData.endTime)] : null}
                  onChange={(date, dateString) => {
                    this.state.modalData.startTime = dateString[0]
                    this.state.modalData.endTime = dateString[1]
                  }}
                  showTime
                />
              </Form.Item>
              <Form.Item style={{float: 'right'}}>
                <Space>
                  <Button onClick={() => this.setState({modalVisible: false, modalData: {id: null}})}>取消</Button>
                  <Button type='primary' htmlType='submit'>确定</Button>
                </Space>
              </Form.Item>
            </Form>
          }
        </Modal>
      </div>
    );
  }
}

export default connect()(TestManager)
